package GameLogic

import (
	"PBMessage"

	"time"

	"git.oschina.net/yangdao/extlib/log"
	"git.oschina.net/yangdao/extlib/math3d"
	"github.com/golang/protobuf/proto"
)

type canRunAbilityState struct {
	*genericState
	pkg *PBMessage.SC_MoveUnit
}

func (this *canRunAbilityState) onEnter(args ...interface{}) {
	this.pkg = &PBMessage.SC_MoveUnit{}
	curAbilty := this.gameUnit.Unit.CurAbility
	//状态切换通知
	state := &PBMessage.SC_UnitState{
		UnitId:   proto.Int64(this.gameUnit.Unit.GUID),
		StringP0: proto.String(curAbilty.Base().Name),
		State:    proto.Int32(2),
		Time:     proto.Int64(time.Now().UnixNano() / 1e6),
	}
	this.gameUnit.Scene.(*GameScene).sendEachPlayer(PBMessage.PBID_SC_UnitState, state)
	curAbilty.Run()
	if curAbilty.Base().BreakMove {
		this.gameUnit.isMoveing = false
	}
	log.Log("GameLogic,Info", "进入到移动技能状态")
}

func (this *canRunAbilityState) onUpdate(dt int) {
	//移动处理
	if this.gameUnit.isMoveing {
		this.gameUnit.setPos(&this.gameUnit.preMovePos, time.Now().UnixNano()/1e6, this.gameUnit.startMoveTime,
			this.gameUnit.Unit.GetProperty(":MoveSpeed").(int))
	}
	//执行结束
	if this.gameUnit.Unit.CurAbility.Base().IsRun() == false {
		if this.gameUnit.isMoveing {
			this.gameUnit.chageState("run")
		} else {
			this.gameUnit.chageState("idle")
		}
		return
	}

	cmd, tuple := this.gameUnit.getCommond()
	switch cmd {
	case CMD_MOVE:
		state := tuple[3].(int32)
		if state == 1 {
			if this.gameUnit.isMoveing {
				this.gameUnit.setPos(&this.gameUnit.preMovePos, tuple[4].(int64), this.gameUnit.startMoveTime,
					this.gameUnit.Unit.GetProperty(":MoveSpeed").(int))
			}
			this.gameUnit.Unit.Dir = math3d.Vec3{X: float64(tuple[1].(int32)), Y: 0, Z: float64(tuple[2].(int32))}
			this.gameUnit.Unit.Dir.Normalize()
			this.gameUnit.startMoveTime = tuple[4].(int64)
			this.gameUnit.preMovePos = this.gameUnit.Unit.Pos()
			this.gameUnit.isMoveing = true
		} else if state == 0 {
			this.gameUnit.isMoveing = false
			this.gameUnit.setPos(&this.gameUnit.preMovePos, tuple[4].(int64), this.gameUnit.startMoveTime,
				this.gameUnit.Unit.GetProperty(":MoveSpeed").(int))
			this.gameUnit.startMoveTime = 0
		}
	case CMD_SPEEDCHANGE:
		nowTime := time.Now().UnixNano() / 1e6
		if this.gameUnit.isMoveing {
			this.gameUnit.setPos(&this.gameUnit.preMovePos, nowTime, this.gameUnit.startMoveTime, this.gameUnit.Speed)
		}
		this.gameUnit.preMovePos = this.gameUnit.Pos()
		this.gameUnit.startMoveTime = nowTime
		this.gameUnit.Speed = this.gameUnit.GetProperty(":MoveSpeed").(int)
		move := this.gameUnit.toSCMove(this.gameUnit.startMoveTime, this.gameUnit.Speed, &this.gameUnit.Dir)
		this.gameUnit.Scene.(*GameScene).sendEachPlayer(PBMessage.PBID_SC_MoveUnit, move)
	}
}
